package cn.itcast.web.controller.cargo;

import cn.itcast.dao.cargo.ShippingOrderDao;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.cargo.PackingService;
import cn.itcast.service.cargo.ShippingOrderService;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/shipping")
@Slf4j
public class ShippingController extends BaseController {
    @Reference
    private ShippingOrderService shippingOrderService;
    @Reference
    private PackingService packingService;

    @Reference
    private ExportService exportService;

    @Reference
    private ContractService contractService;

    @RequestMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize){
        PageInfo<ShippingOrder> pageInfo = shippingOrderService.findByPage(pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/shipping/shipping-list";
    }

    @RequestMapping("/save")
    public String save(ShippingOrder shippingOrder){
        shippingOrder.setCheckBy(getLoginUser().getId());
        shippingOrder.setCreateTime(new Date());
        shippingOrder.setCreateDept(getLoginUser().getDeptId());
        shippingOrderService.save(shippingOrder);
        Packing packing = packingService.findById(shippingOrder.getShippingOrderId());
        packing.setState(1);
        packingService.update(packing);

        return "redirect:/cargo/shipping/list";

    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "redirect:/cargo/packing/list";
    }

    @RequestMapping("/delete")
    public String delete(String id) {
        ShippingOrder shippingOrder = shippingOrderService.findById(id);
        if (shippingOrder.getState()==0){
            shippingOrderService.delete(id);
        }
        return "redirect:/cargo/shipping/list";
    }

    /**
     * 生成发票
     *
     * @param id 委托单id
     */
    @RequestMapping("/invoice")
    public String invoice(String id) {
        Packing packing = packingService.findById(id);
        //装箱金额
        Double packingMoney = packing.getPackingMoney();

        String exportIds = packing.getExportIds();
        String[] exportId = exportIds.split(",");
        Export export = exportService.findById(exportId[0]);
        //货运金额



        String contractIds = export.getContractIds();
        Contract contract = contractService.findById(contractIds);

        Integer invoiceMoney=0;
        request.setAttribute("packing",packing);
        request.setAttribute("contract",contract);
        request.setAttribute("invoiceMoney",1521);

        return "cargo/invoice/invoice-add";
    }


    @RequestMapping("/printExcel")
    public void printExcel(String id) throws IOException {
        //【获取excel模板,文件流】
        InputStream in = request.getSession()
                .getServletContext()
                .getResourceAsStream("/make/xlsprint/tSHIPPINGORDER.xls");

        // 第一：导出第一行
        Workbook workbook = new HSSFWorkbook(in);
        // 【获取工作表】
        Sheet sheet = workbook.getSheetAt(0);


        // 第三：导出数据库（调用service）
        ShippingOrder shippingOrder = shippingOrderService.findById(id);
        Packing packing = packingService.findById(id);
                // 创建每一个数据行，从第三行开始
                 Row row = sheet.getRow(3);

        Cell cell = row.getCell(0);
        if (shippingOrder.getShipper()!=null){
        cell.setCellValue(shippingOrder.getShipper());
        }

        row = sheet.getRow(8);
         cell = row.getCell(0);
        if (shippingOrder.getConsignee()!=null){
            cell.setCellValue(shippingOrder.getConsignee());
        }

        row = sheet.getRow(15);
        cell = row.getCell(0);
        if (shippingOrder.getNotifyParty()!=null){
            cell.setCellValue(shippingOrder.getNotifyParty());
        }

        //发票号
      /*
        cell = row.getCell(0);
        if (shippingOrder.()!=null){
            cell.setCellValue(shippingOrder.getNotifyParty());
        }*/

      //时间
        row = sheet.getRow(19);
        cell = row.getCell(3);
        cell.setCellValue(new Date());


        cell = row.getCell(6);
        if (shippingOrder.getLcNo()!=null){
            cell.setCellValue(shippingOrder.getLcNo());
        }

        row = sheet.getRow(23);
        cell = row.getCell(0);
        if (shippingOrder.getPortOfLoading()!=null){
            cell.setCellValue(shippingOrder.getPortOfLoading());
        }

        cell = row.getCell(3);
        if (shippingOrder.getPortOfTrans()!=null){
            cell.setCellValue(shippingOrder.getPortOfTrans());
        }

        cell = row.getCell(6);
        if (shippingOrder.getPortOfDischar()!=null){
            cell.setCellValue(shippingOrder.getPortOfDischar());
        }
        row = sheet.getRow(27);
        cell = row.getCell(0);
        if (shippingOrder.getLoadingDate()!=null){
            cell.setCellValue(shippingOrder.getLoadingDate());
        }

        row = sheet.getRow(27);
        cell = row.getCell(2);
        if (shippingOrder.getLimitTime()!=null){
            cell.setCellValue(shippingOrder.getLimitTime());
        }

        row = sheet.getRow(27);
        cell = row.getCell(3);
        if (shippingOrder.getIsBatch()!=null){
            if (shippingOrder.getIsBatch()=="0"){
                cell.setCellValue("不分批");
            }else {
                cell.setCellValue("分批");
            }
        }

        row = sheet.getRow(27);
        cell = row.getCell(5);
        if (shippingOrder.getIsTrans()!=null){
            if (shippingOrder.getIsTrans()=="0"){
                cell.setCellValue("不转船");
            }else {
                cell.setCellValue("转船");
            }
        }

        row = sheet.getRow(27);
        cell = row.getCell(7);
        if (shippingOrder.getCopyNum()!=null){
            cell.setCellValue(shippingOrder.getCopyNum());
        }

        row = sheet.getRow(31);
        cell = row.getCell(0);
        if (packing.getMarks()!=null){
            cell.setCellValue(packing.getMarks());
        }

        row = sheet.getRow(31);
        cell = row.getCell(3);
        if (packing.getDescription()!=null){
            cell.setCellValue(packing.getDescription());
        }

        row = sheet.getRow(31);
        cell = row.getCell(5);
        if (packing.getNetWeights()!=null&&packing.getGrossWeights()!=null){
            cell.setCellValue(packing.getNetWeights()+packing.getGrossWeights());
        }

        row = sheet.getRow(31);
        cell = row.getCell(6);
        if (packing.getNetWeights()!=null){
            cell.setCellValue(packing.getNetWeights());
        }

        //Measurement
       /* row = sheet.getRow(31);
        cell = row.getCell(8);
        if (packing.getNetWeights()!=null){
            cell.setCellValue(packing.getNetWeights());
        }*/

        row = sheet.getRow(37);
        cell = row.getCell(1);
        if (shippingOrder.getSpecialCondition()!=null){
            cell.setCellValue(shippingOrder.getSpecialCondition());
        }
        // 第四：导出下载
        response.setCharacterEncoding("UTF-8");
        // 设置下载响应头（浏览器会以下载方式处理响应结果）
        response.setHeader("content-disposition","attachment;filename=ship.xls");
        ServletOutputStream out = response.getOutputStream();
        // 把excel文件流，写入到response输出流，实现下载
        workbook.write(out);
        workbook.close();
        out.close();
    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }


}
